import Vue from 'vue';
import Vuex from 'vuex';
import {nanoid} from 'nanoid';
import dataFormat from '@/utils/dateFormat';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    tagsList: [] as Tag[],
    record: {
      type: '-',
      note: '',
      amount: 0,
      selectedTagsList: []
    } as RecordItem,
    recordList: [] as RecordItem[],
    showDate:'day',
    recordResultList:[] as HashTableValue[]
  },
  mutations: {
    fetchTagsList(state,) {
      state.tagsList = JSON.parse(localStorage.getItem('tagsList') || '[]');
    },

    saveTagsList(state) {
      localStorage.setItem('tagsList', JSON.stringify(state.tagsList));
    },

    addTag(state) {
      const tag: string | null = prompt('请输入标签名：');
      if (!tag) return;

      const t = state.tagsList.map(item => item.tagName);

      //如果tagsList里不存在输入的标签
      if (!(t).includes(tag)) {
        //添加标签到列表
        state.tagsList = [...state.tagsList, {id: nanoid(8), tagName: tag}];
      } else {
        alert('标签不能重复');
      }
    },

    delTag(state, id: string) {
      state.tagsList = state.tagsList.filter(tag => {
        return tag.id != id;
      });
    },

    changeTagName(state, newTag) {

      for (let i = 0; i < state.tagsList.length; i++) {
        if (state.tagsList[i].tagName === newTag.tagName) {
          alert('标签名已存在');
          return;
        }
      }

      for (let i = 0; i < state.tagsList.length; i++) {
        if (state.tagsList[i].id === newTag.id) {
          state.tagsList[i].tagName = newTag.tagName;
          return;
        }
      }
    },

    fetchRecordList(state) {
      state.recordList = JSON.parse(localStorage.getItem('recordList') || '[]');
    },

    updateRecord(state, dateObj) {
      state.record.id = nanoid();
      state.record.date = dataFormat("YYYY-mm-dd HH:MM", new Date())
      state.record[dateObj.name] = dateObj.value;
    },

    addRecord(state, date: RecordItem) {
      state.recordList.push(date);
    },

    saveRecordList(state) {
      localStorage.setItem('recordList', JSON.stringify(state.recordList));
    },

    cleanRecord(state) {
      state.record.selectedTagsList = [];
      state.record.note = '';
    }
  },
});
